package com.newly.center.business.service.impl;

import cn.hutool.json.JSONObject;
import com.newly.center.business.service.MQTTOTAService;
import com.newly.common.base.entity.R;
import com.newly.driver.mqtt.utils.MqttUtils;
import com.newly.driver.mqtt.utils.ReturnResult;
import com.newly.transfer.redis.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.IOException;

@Service("mqttOTAService")
public class MQTTOTAServiceImpl implements MQTTOTAService {
    @Autowired
    RedisUtils redisUtils;
    
    @Override
    public R setOTAByFile(String productKey, MultipartFile file) {
        String token = redisUtils.get("mqtt"+productKey,String.class);
        String requestTopic = "/sys/device/"+ productKey+"/command/request/request-id=0x50000001";
        String responseTopic = "/sys/device/"+ productKey+"/command/response/request-id=0x50000001";

        BASE64Encoder encoder = new BASE64Encoder();
        String encode = null;
        try {
            encode = encoder.encode(file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject result = new JSONObject();
        result.put("version","1.0");
        result.put("id",productKey);
        result.put("token",token);
        JSONObject ota = new JSONObject();
        ota.put("mode","binary");
        ota.put("data",encode);
        JSONObject params = new JSONObject();
        params.put("ota",ota);
        result.put("params",params);

        MqttUtils.publishMessage(requestTopic,result,1);
        return ReturnResult.getResult(responseTopic,redisUtils);
    }

    @Override
    public R setOTAByHttp(String productKey,String fileUrl) {
        String token = redisUtils.get("mqtt"+productKey,String.class);
        String requestTopic = "/sys/device/"+ productKey+"/command/request/request-id=0x50000001";
        String responseTopic = "/sys/device/"+ productKey+"/command/response/request-id=0x50000001";

        JSONObject result = new JSONObject();
        result.put("version","1.0");
        result.put("id",productKey);
        result.put("token",token);
        JSONObject ota = new JSONObject();
        ota.put("mode","http");
        ota.put("data",fileUrl);
        JSONObject params = new JSONObject();
        params.put("ota",ota);
        result.put("params",params);

        MqttUtils.publishMessage(requestTopic,result,1);
        return ReturnResult.getResult(responseTopic,redisUtils);
    }
}
